﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Serialization;

namespace Limestone
{
    [Serializable]
    public class FieldCollection : Collection<Field>
    {
        [XmlIgnore]
        public Page Page { get; set; }

        protected override void InsertItem(int index, Field newItem)
        {
            //newItem.FieldCollection = this;
            base.InsertItem(index, newItem);
            ResetIndices();

        }

        protected override void SetItem(int index, Field newItem)
        {
            base.SetItem(index, newItem);

            // TODO - verify that this is correct. Should i call remove? does newItem really have an id yet?

            // remove the item that is being replaced
            RemoveItem(index);

            //   newItem.FieldCollection = this;
            InsertItem(index, newItem);
            ResetIndices();
        }

        protected override void RemoveItem(int index)
        {
            // IField removedItem = Items[index];
            base.RemoveItem(index);
            ResetIndices();
        }

        public Field this[string fieldName]
        {
            get
            {
                return Items.FirstOrDefault(item => item.Name.ToLower() == fieldName.ToLower());
            }
            set
            {
                var idx = 0;
                foreach (var item in Items)
                {
                    if (item.Name.ToLower() == fieldName.ToLower())
                    {
                        SetItem(idx, value);
                        break;
                    }
                    idx++;
                }
            }
        }

        /// <summary>
        /// Helper function to re-enumerate the index property of the fields if it has been garbled or messed up
        /// </summary>
        public void ResetIndices()
        {
            var idx = 0;
            foreach (var field in Items.OrderBy(f => f.Index))
            {
                field.Index = idx;
                idx++;
            }
        }
    }

}

